# -*- coding: utf-8 -*-
__author__ = 'Paul'
import random
from zope import schema
from zope.formlib import form
from zope.interface import implements
from zope.component import getMultiAdapter
from plone.app.portlets.portlets import base
from plone.memoize.instance import memoize
from plone.portlets.interfaces import IPortletDataProvider
from DateTime import DateTime
from Products.Five.browser.pagetemplatefile import\
    ViewPageTemplateFile
from Products.CMFCore.utils import getToolByName
from Products.bpContents import _
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from Acquisition import aq_inner
from plone.memoize.compress import xhtml_compress
from Products.bpContents.aviso import IAviso
from Products.ATContentTypes.interfaces import IATDocument
from Products.bpContents.galeria import IGaleria
from zope.site.hooks import getSite
from OFS.interfaces import IOrderedContainer
import unicodedata


class IGaleriasPortlet(IPortletDataProvider):
    count = schema.Int(title=_(u'Number of items to display'),
        description=_(u'How many items to list.'),
        required=True,
        default=3)



class Assignment(base.Assignment):
    implements(IGaleriasPortlet)

    def __init__(self, count=5,canal=[], categoria=[]):
        self.count = count

    @property
    def title(self):
        return _(u"Galerias Multimedia")

class Renderer(base.Renderer):
    render = ViewPageTemplateFile('galerias_portlets.pt')

    def __init__(self, *args):
        base.Renderer.__init__(self, *args)
        context = aq_inner(self.context)
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
        plone_tools = getMultiAdapter((context, self.request), name=u'plone_tools')
        self.atvm = getToolByName(context , 'portal_vocabularies')
        self.catalog = plone_tools.catalog()
        self.anonymous = portal_state.anonymous()
        self.portal_url = portal_state.portal_url()


    @property
    def available(self):
        return True
        #len(self._data())>0

    def getRamas(self):
        return self._data()

    @memoize
    def _data(self):
        ramas=[]

        baseObje=getSite()["home"]["galerias"]
        rutaBase="/".join(baseObje.getPhysicalPath())
        catalogo=self.catalog({'object_provides': IGaleria.__identifier__,'path': {'query': rutaBase, 'depth': 1}})
        flagRama=0

        for ramaIndice in catalogo:
            miObj=self.context.unrestrictedTraverse(ramaIndice.getPath())
            mainObject=miObj

            if mainObject.tipoGaleria=="Multimedia":
                flagItem=0
                resumen=ramaIndice.Description
                if len(resumen)>60:
                    resumen=resumen[:ramaIndice.Description[:60].rfind(" ")]+" ..."
                objRama=dict()
                objRama['titulo']=mainObject.nombre
                objRama['descri']=resumen
                retrato=self.getImages(mainObject)

                if retrato and len(retrato)>0:
                    objRama["retrato"]=self.getImages(mainObject)[0]
                else:
                    objRama["retrato"]=None
                objRama["url"]=ramaIndice.getPath()
                objRama['position']=self.get_position_in_parent(mainObject)
                ramas.append(objRama)
        return sorted(ramas)

    def get_position_in_parent(self,obj):
        """ Use IOrderedContainer interface to extract the object's manual ordering position
        """
        parent = obj.aq_inner.aq_parent
        ordered = IOrderedContainer(parent, None)
        if ordered is not None:
            return ordered.getObjectPosition(obj.getId())
        return 0

    def getImages(self,obj):
        """Toda las imagenes
        """
        from Products.bpContents.getImgTira import GetTiraImgs
        context = GetTiraImgs(obj)
        results = context.getTira()
        if results:
            return results
        else:
            return None

class AddForm(base.AddForm):
    form_fields = form.Fields(IGaleriasPortlet)
    label = _(u"Add Recent Portlet")
    description = _(u"This portlet displays recently modified content.")

    def create(self, data):
        return Assignment(count=data.get('count', 3))

class EditForm(base.EditForm):
    form_fields = form.Fields(IGaleriasPortlet)
    label = _(u"Edit Recent Portlet")
    description = _(u"This portlet displays recently modified content.")